/**
 * 工时统计数据管理 Hook
 */

'use client';

import { useState, useCallback, useEffect } from 'react';
import { message } from 'antd';
import { 
  ProjectWorkloadSummary, 
  WorkloadStatsQueryParams,
  WorkloadChartData,
  TimeSeriesData,
  ProjectComparisonData
} from '@/types/workloadStats';
import { WorkloadRecord } from '@/types/workload';
import { pingCodeAPI } from '@/utils/pingcodeApi';

export function useWorkloadStats() {
  const [loading, setLoading] = useState(false);
  const [projectSummaries, setProjectSummaries] = useState<ProjectWorkloadSummary[]>([]);
  const [chartData, setChartData] = useState<WorkloadChartData[]>([]);
  const [timeSeriesData, setTimeSeriesData] = useState<TimeSeriesData[]>([]);
  const [comparisonData, setComparisonData] = useState<ProjectComparisonData[]>([]);
  const [selectedProject, setSelectedProject] = useState<ProjectWorkloadSummary | null>(null);
  const [projectDetails, setProjectDetails] = useState<WorkloadRecord[]>([]);
  const [detailLoading, setDetailLoading] = useState(false);

  // 获取工时统计数据
  const fetchWorkloadStats = useCallback(async (params: WorkloadStatsQueryParams = {}) => {
    setLoading(true);
    try {
      console.log('获取工时统计数据，参数：', params);

      // 构建查询参数
      const queryParams: any = {
        page: 0,
        page_size: 100, // API限制最大100
        ...params
      };

      // 如果有日期范围，添加到查询参数
      if (params.startDate) {
        queryParams.start_date = params.startDate;
      }
      if (params.endDate) {
        queryParams.end_date = params.endDate;
      }
      if (params.projectIds && params.projectIds.length > 0) {
        queryParams.pilot_id = params.projectIds[0]; // API 只支持单个项目查询
        queryParams.principal_type = 'work_item'; // 查询工作项类型的工时
      }

      // 分页获取所有工时数据
      let allWorkloads: WorkloadRecord[] = [];
      let page = 0;
      let hasMore = true;
      
      while (hasMore) {
        const currentParams = { ...queryParams, page };
        const response = await pingCodeAPI.getWorkloads(currentParams);
        console.log(`获取第 ${page + 1} 页工时数据，响应：`, response);

        if (response && response.values && response.values.length > 0) {
          allWorkloads = [...allWorkloads, ...response.values];
          page++;
          hasMore = response.values.length === 100;
          console.log(`已获取第 ${page} 页工时数据，当前总数: ${allWorkloads.length}`);
        } else {
          hasMore = false;
        }
      }

      if (allWorkloads.length > 0) {
        // 处理统计数据
        const summaries = processWorkloadData(allWorkloads);
        setProjectSummaries(summaries);

        // 生成图表数据
        const charts = generateChartData(summaries);
        setChartData(charts);

        // 生成时间序列数据
        const timeSeries = generateTimeSeriesData(allWorkloads);
        setTimeSeriesData(timeSeries);

        // 生成项目对比数据
        const comparison = generateComparisonData(summaries);
        setComparisonData(comparison);

        message.success(`成功加载 ${summaries.length} 个项目的工时统计数据，共 ${allWorkloads.length} 条记录`);
      } else {
        message.warning('未找到符合条件的工时记录');
        setProjectSummaries([]);
        setChartData([]);
        setTimeSeriesData([]);
        setComparisonData([]);
      }
    } catch (error) {
      console.error('获取工时统计数据失败：', error);
      message.error('获取工时统计数据失败');
      setProjectSummaries([]);
      setChartData([]);
      setTimeSeriesData([]);
      setComparisonData([]);
    } finally {
      setLoading(false);
    }
  }, []);

  // 获取项目详细工时记录
  const fetchProjectDetails = useCallback(async (projectId: string, params: WorkloadStatsQueryParams = {}) => {
    setDetailLoading(true);
    try {
      console.log('获取项目详细工时记录，项目ID：', projectId);

      const queryParams: any = {
        page: 0,
        page_size: 100, // API限制最大100
        pilot_id: projectId,
        principal_type: 'work_item', // 查询工作项类型的工时
        ...params
      };

      if (params.startDate) {
        queryParams.start_date = params.startDate;
      }
      if (params.endDate) {
        queryParams.end_date = params.endDate;
      }

      // 分页获取所有项目工时数据
      let allWorkloads: WorkloadRecord[] = [];
      let page = 0;
      let hasMore = true;
      
      while (hasMore) {
        const currentParams = { ...queryParams, page };
        const response = await pingCodeAPI.getWorkloads(currentParams);
        console.log(`获取项目 ${projectId} 第 ${page + 1} 页工时数据`);

        if (response && response.values && response.values.length > 0) {
          allWorkloads = [...allWorkloads, ...response.values];
          page++;
          hasMore = response.values.length === 100;
        } else {
          hasMore = false;
        }
      }

      if (allWorkloads.length > 0) {
        setProjectDetails(allWorkloads);
        message.success(`成功加载 ${allWorkloads.length} 条工时记录`);
      } else {
        message.warning('未找到符合条件的工时记录');
        setProjectDetails([]);
      }
    } catch (error) {
      console.error('获取项目详细工时记录失败：', error);
      message.error('获取项目详细工时记录失败');
      setProjectDetails([]);
    } finally {
      setDetailLoading(false);
    }
  }, []);

  // 处理工时数据，生成项目汇总
  const processWorkloadData = (workloads: WorkloadRecord[]): ProjectWorkloadSummary[] => {
    const projectMap = new Map<string, {
      projectId: string;
      projectName: string;
      projectIdentifier: string;
      records: WorkloadRecord[];
      members: Set<string>;
      workloadTypes: Set<string>;
    }>();

    // 按项目分组
    workloads.forEach(record => {
      const projectId = record.pilotId || 'unknown';
      const projectName = record.pilotName || '未知项目';
      const projectIdentifier = record.pilotIdentifier || '';

      if (!projectMap.has(projectId)) {
        projectMap.set(projectId, {
          projectId,
          projectName,
          projectIdentifier,
          records: [],
          members: new Set(),
          workloadTypes: new Set()
        });
      }

      const project = projectMap.get(projectId)!;
      project.records.push(record);
      project.members.add(record.memberId);
      project.workloadTypes.add(record.workloadTypeName || '');
    });

    // 生成汇总数据
    const summaries: ProjectWorkloadSummary[] = [];
    
    projectMap.forEach(project => {
      const totalHours = project.records.reduce((sum, record) => sum + record.hours, 0);
      const memberCount = project.members.size;
      
      // 计算工作日数（按日期去重）
      const workDates = new Set(
        project.records
          .filter(r => r.date) // 过滤掉没有日期的记录
          .map(r => r.date.split('T')[0])
      );
      const workDays = workDates.size;
      
      const avgDailyHours = workDays > 0 ? totalHours / workDays : 0;
      
      // 计算日期范围
      const validDates = project.records
        .filter(r => r.date) // 过滤掉没有日期的记录
        .map(r => new Date(r.date));
      
      const startDate = validDates.length > 0 
        ? new Date(Math.min(...validDates.map(d => d.getTime()))).toISOString()
        : new Date().toISOString();
      const endDate = validDates.length > 0
        ? new Date(Math.max(...validDates.map(d => d.getTime()))).toISOString()
        : new Date().toISOString();

      // 生成成员统计
      const memberStats = generateMemberStats(project.records, totalHours);

      summaries.push({
        projectId: project.projectId,
        projectName: project.projectName,
        projectIdentifier: project.projectIdentifier,
        totalHours,
        memberCount,
        workDays,
        avgDailyHours,
        startDate,
        endDate,
        workloadTypes: Array.from(project.workloadTypes),
        memberStats
      });
    });

    return summaries.sort((a, b) => b.totalHours - a.totalHours);
  };

  // 生成成员统计数据
  const generateMemberStats = (records: WorkloadRecord[], totalProjectHours: number) => {
    const memberMap = new Map<string, {
      memberId: string;
      memberName: string;
      records: WorkloadRecord[];
    }>();

    records.forEach(record => {
      const memberId = record.memberId;
      const memberName = record.memberName || '未知成员';

      if (!memberMap.has(memberId)) {
        memberMap.set(memberId, {
          memberId,
          memberName,
          records: []
        });
      }

      memberMap.get(memberId)!.records.push(record);
    });

    return Array.from(memberMap.values()).map(member => {
      const totalHours = member.records.reduce((sum, record) => sum + record.hours, 0);
      const workDates = new Set(
        member.records
          .filter(r => r.date) // 过滤掉没有日期的记录
          .map(r => r.date.split('T')[0])
      );
      const workDays = workDates.size;
      const avgDailyHours = workDays > 0 ? totalHours / workDays : 0;
      const percentage = totalProjectHours > 0 ? (totalHours / totalProjectHours) * 100 : 0;

      return {
        memberId: member.memberId,
        memberName: member.memberName,
        totalHours,
        workDays,
        avgDailyHours,
        percentage
      };
    }).sort((a, b) => b.totalHours - a.totalHours);
  };

  // 生成图表数据
  const generateChartData = (summaries: ProjectWorkloadSummary[]): WorkloadChartData[] => {
    const totalHours = summaries.reduce((sum, project) => sum + project.totalHours, 0);
    
    return summaries.map(project => ({
      name: project.projectName,
      value: project.totalHours,
      hours: project.totalHours,
      percentage: totalHours > 0 ? (project.totalHours / totalHours) * 100 : 0
    }));
  };

  // 生成时间序列数据
  const generateTimeSeriesData = (workloads: WorkloadRecord[]): TimeSeriesData[] => {
    const dateMap = new Map<string, { hours: number; projects: Map<string, number> }>();

    workloads.forEach(record => {
      if (!record.date) return; // 跳过没有日期的记录
      
      const date = record.date.split('T')[0];
      const projectName = record.pilotName || '未知项目';

      if (!dateMap.has(date)) {
        dateMap.set(date, { hours: 0, projects: new Map() });
      }

      const dayData = dateMap.get(date)!;
      dayData.hours += record.hours;
      dayData.projects.set(projectName, (dayData.projects.get(projectName) || 0) + record.hours);
    });

    return Array.from(dateMap.entries())
      .map(([date, data]) => ({
        date,
        hours: data.hours,
        projects: Object.fromEntries(data.projects)
      }))
      .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
  };

  // 生成项目对比数据
  const generateComparisonData = (summaries: ProjectWorkloadSummary[]): ProjectComparisonData[] => {
    return summaries.map(project => ({
      projectName: project.projectName,
      totalHours: project.totalHours,
      memberCount: project.memberCount,
      avgDailyHours: project.avgDailyHours,
      efficiency: project.memberCount > 0 ? project.totalHours / project.memberCount : 0
    }));
  };

  return {
    loading,
    projectSummaries,
    chartData,
    timeSeriesData,
    comparisonData,
    selectedProject,
    projectDetails,
    detailLoading,
    fetchWorkloadStats,
    fetchProjectDetails,
    setSelectedProject
  };
}